package com.central.oauth.handler;

import com.alibaba.fastjson.JSON;
import com.central.common.model.Result;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

/**
 * @author: ly
 * @date: 2020/11/23 3:24 下午
 * @email: 664162337@qq.com
 */
public class OauthLoginAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException e) throws IOException {
        // 防止中文乱码问题
        String msg = e.getMessage();
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        if (e instanceof BadCredentialsException) {
            msg = "账号或密码错误";
        }
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(Result.failed(msg)));
        writer.flush();
    }
}
